package com.zjjt.dc.modules.datacatch.util.api.client;


import com.zjjt.dc.modules.datacatch.util.api.config.BLHApiConfig;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class BLHApiClient {

    private static final String CONTENT_TYPE = "application/json";

    private final BLHApiConfig config;

    public BLHApiClient(BLHApiConfig config) {
        this.config = config;
    }

    /**
     * 发送 HTTP POST 请求
     *
     * @param path        请求路径
     * @param jsonPayload JSON 格式的请求体
     * @return 响应体字符串
     */
    public String SendRequest(String path, String jsonPayload) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .followRedirects(HttpClient.Redirect.NORMAL)
                .connectTimeout(Duration.ofSeconds(20))
                .build();

        String apiUrl = this.config.getBaseUrl() + path;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(apiUrl))
                .header("Content-Type", CONTENT_TYPE)
                .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new IOException("HTTP 请求失败，状态码: " + response.statusCode() + ", 响应内容: " + response.body());
        }
    }
}
